package com.randb.easyhttp.subscriber;

import android.content.Context;

import com.randb.easyhttp.exception.ApiException;
import com.randb.easyhttp.utils.HttpLog;
import com.randb.easyhttp.utils.Utils;

import java.lang.ref.WeakReference;

import io.reactivex.observers.DisposableObserver;

/**
 * User: RandBII
 * Date: 2020/5/11
 * Description:
 */
public abstract class BaseSubscriber<T> extends DisposableObserver<T> {
    public WeakReference<Context> weakReference;

    public BaseSubscriber() {

    }

    public BaseSubscriber(Context context) {
        weakReference = new WeakReference<>(context);
    }


    @Override
    protected void onStart() {
        if (weakReference != null &&
                weakReference.get() != null
                && !Utils.getNetWorkAvailable(weakReference.get())) { // 无网络结束
            onComplete();
        }
    }

    @Override
    public void onNext(T t) {

    }


    @Override
    public void onError(Throwable e) {
        if (e instanceof ApiException) {
            HttpLog.e("--> e instanceof ApiException err:" + e);
            onError((ApiException) e);
        } else {
            HttpLog.e("--> e !instanceof ApiException err:" + e);
            onError(ApiException.handleException(e));
        }
    }

    public abstract void onError(ApiException e);
}
